<template>
    <BasePopPanel
        title="图层"
        type="right"
        :right="showRight ? '1010px' : '150px'"
        width="248px"
        height="560px"
        :show-close="false"
        class="reset-layer-tool-panel-box"
    >
        <ElScrollbar style="width: 100%; height: 100%">
            <LayerTreeCheck
                ref="layerTreeCheckRef"
                :default-value="defaultChecked"
                :tree-data="treeData"
                @check-change="onCheckChange"
            />
        </ElScrollbar>
    </BasePopPanel>
</template>

<script setup lang="ts">
import { useTemplateRef } from 'vue'
import BasePopPanel from '@/components/BasePopPanel/index.vue'
import LayerTreeCheck from '@/components/LayerTreeCheck/index.vue'
import { addTestGroupOnePointLayer, removeCombinedLayers } from '@/utils/map-tools'
import { useGlobalStore } from '@/store/global'
const globalStore = useGlobalStore()
const showRight = computed(() => globalStore.showPageRight)

// 默认选择的图层
const defaultChecked = ref<string[]>([])

// icon定义
const ICON_CONFIG = {
    country: 'layer-tool-panel/gas/guo.png'
}

// 图层数据结构
const LAYER_TREE_DATA = [
    {
        key: 'gas',
        label: '环境监测点',
        children: [
            {
                key: 'country',
                label: '示例点位',
                value: 1,
                icon: ICON_CONFIG.country
            }
        ]
    }
]
// 图层定义
const treeData = ref(LAYER_TREE_DATA)

// 监听图层修改
const layerTreeCheckRef = useTemplateRef('layerTreeCheckRef')
const previousCheckedLayers = ref<string[]>([])
const onCheckChange = () => {
    const currentCheckedLayers = layerTreeCheckRef.value?.getAllCheckedKeys() || []
    // 使用 Set 提高查找效率
    const previousSet = new Set(previousCheckedLayers.value)
    const currentSet = new Set(currentCheckedLayers)

    // 找出新增的图层
    const addedLayers = currentCheckedLayers.filter(layer => !previousSet.has(layer))
    addedLayers.forEach(layer => {
        addTestGroupOnePointLayer(layer)
    })

    // 找出删除的图层
    const removedLayers = previousCheckedLayers.value.filter(layer => !currentSet.has(layer))
    removedLayers.forEach(layer => {
        removeCombinedLayers([layer])
    })
    
    previousCheckedLayers.value = currentCheckedLayers
}

onMounted(() => {
    defaultChecked.value = ['country']
})

// 卸载图层
onUnmounted(() => {
    if (window.glPopup) window.glPopup.remove()
})
</script>
